/**
 * 转充话费
 * @authors supmain (mtingfeng@gmail.com)
 * @date    2015-02-02 14:28:55
 * @for turn_bill.html
 */
var BSTYUN = BSTYUN || {};
BSTYUN.turnbill = {
	init: function(){
		var that = this;
		that.initTurnBill();
	},
	initTurnBill: function(){
		var $tel_charge = $("#tel_charge"),
			$turnsuccess = $("#turnsuccess"),
			$continue_turnbill = $(".continue_turnbill");
		var $remain = $("#remain"),
			$transferbill = $("#transferbill"),
			$paypsd = $("#paypsd"),
			$brn_bar = $(".brn_bar");
		/* 转充话费 */
		$brn_bar.on("click",".confirm",function(){
			var data = getData();
			if( checkData( data ) ){
				updateDataToInput( data );
				$.ajax({
					url: '/path/to/file',
					type: 'post',
					dataType: 'json',
					data: data,
					beforeSend: null,
					complete: null,
					success: function( data ){
						if( data.isSuccess ){
							showTurnBillSuccess();
						};
					},
					error: function(){
						
					}
				});
			};
		});
		function getData(){
			return {
				reamin : $.trim( $remain.text() ),
				transferbill : $.trim( $transferbill.val() ),
				psd : $.trim( $paypsd.val() )
			};
		};
		function checkData( data ){
			if( data.transferbill == "" ){
				BSTYUN.dialog.warn("转充金额不能为空！");
				return false;
			};
			if( !/^\d*(\.\d+)?$|^\d+(\.\d*)?$/gi.test( data.transferbill ) ){ // 是否是数字: '.123' 、 '123.' 都合法
				BSTYUN.dialog.warn("请输入正确的金额！");
				return false;
			}else{
				try{
					data.transferbill = Number( data.transferbill );
				}catch( e ){
					BSTYUN.dialog.warn("请输入正确的金额！");
					return false;
				};
			};
			if( data.reamin < data.transferbill ){
				BSTYUN.dialog.warn("余额不足，请充值！");
				return false;
			};
			if( data.psd == "" ){
				BSTYUN.dialog.warn("支付密码不能为空！");
				return false;
			};
			return true;
		};
		function updateDataToInput( data ){
			if( "transferbill" in data ){
				$transferbill.val( data.transferbill );
			};
		};
		/* 继续充值 */
		$continue_turnbill.on("click",function(){
			$tel_charge.show();
			$turnsuccess.hide();
		});
		/* 充值成功 */
		function showTurnBillSuccess(){
			$tel_charge.hide();
			$turnsuccess.show();
		};
	}
};
$(function(){
	BSTYUN.turnbill.init();
});